package com.j.lemon.learn.thread.CAS;

import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * @Author lijunjun
 * @Date 2019-04-17 16:05
 * @Description ABA问题解决,使用带有版本号的原子引用
 */
public class ABADemo {
    private static AtomicReference<Integer> atomicReference = new AtomicReference<>(100);
    private static AtomicStampedReference<Integer> atomicStampedReference = new AtomicStampedReference<>(100,1);
    public static void main(String[] args) throws InterruptedException {
        new Thread(()->{
            atomicReference.compareAndSet(100,101);
            atomicReference.compareAndSet(101,100);
        },"t1").start();
        Thread.sleep(1000);
        new Thread(()->{
            atomicReference.compareAndSet(100,102);
        },"t2").start();
        Thread.sleep(1000);
        System.out.println(atomicReference.get());


        new Thread(()->{
            int stamp = atomicStampedReference.getStamp();
            atomicStampedReference.compareAndSet(100,101,stamp,stamp+1);
            int stamp1 = atomicStampedReference.getStamp();
            atomicStampedReference.compareAndSet(101,100,stamp1,stamp1+1);
        },"t3").start();
        Thread.sleep(1000);
        new Thread(()->{
            System.out.println(atomicStampedReference.compareAndSet(100, 2019, 1, 2));
            System.out.println(atomicStampedReference.getReference());
        },"t4").start();



    }
}
